/**
 * @description 多选选组件
 * @author 大肘子
 */

import React, { FC, useEffect, useState } from 'react'
import style from './index.module.scss'

type QuestionCheckboxType = {
  fe_id: string
  props: {
    title: string
    isvertical: boolean
    list: Array<{ text: string; value: string; checked: boolean }>
  }
}

const QuestionCheckbox: FC<QuestionCheckboxType> = ({ fe_id, props }) => {
  const { title, isvertical = false, list = [] } = props
  const [selectValues, setselectValues] = useState<string[]>([])
  //初始化默认选择
  useEffect(() => {
    list.forEach(c => {
      const { value, checked } = c
      if (checked) {
        setselectValues(selectValues => selectValues.concat([value]))
      }
    })
  }, [list])
  //切换选中状态
  function togglechange(value: string) {
    if (selectValues.includes(value)) {
      setselectValues(selectValues => {
        return selectValues.filter(item => {
          return item != value
        })
      })
    } else {
      setselectValues(selectValues.concat([value]))
    }
  }

  const classname = isvertical ? 'isvertival' : 'ishorizon'
  return (
    <>
      <p className={style.title}>{title}</p>
      {/* 建立隐藏域  用来提交chenckbox的值 */}
      <input type='hidden' name={fe_id} value={selectValues.toString()} />
      {/* 建立隐藏域  用来提交chenckbox的值 */}
      <div className={`${style.question} ${style[classname]}`}>
        {list.map(({ text, value: val, checked }, index) => {
          return (
            <div key={index} className={style.radioitem}>
              <label>
                {/* <input type='checkbox' name={fe_id} value={val}  defaultChecked={checked} ></input> */}
                <input
                  checked={selectValues.includes(text)}
                  type="checkbox"
                  onChange={() => {
                    togglechange(text)
                  }}
                ></input>
                <span className={style.radiospan}>{text}</span>
              </label>
            </div>
          )
        })}
      </div>
    </>
  )
}

export default QuestionCheckbox
